﻿Imports SonOVB.Samples.ComicSyndication.ComicProvider
Imports SonOVB.Samples.ComicSyndication.Extensions
Imports SonOVB.Samples.ComicSyndication.Configuration
Imports System.IO
Imports System.Text
Imports System.Web
Imports System.Net
Imports System.Drawing.Imaging
Imports System.Threading
Imports System.Diagnostics


<ServiceBehavior(ConcurrencyMode:=ConcurrencyMode.Single)> _
Public Class ComicService
    Implements IComicService


    ''' <summary>
    ''' 漫画缩略图大小
    ''' </summary>
    ''' <remarks></remarks>
    Private Const INT_ComicThumbnailImageSize As Integer = 250
    ''' <summary>
    ''' 内容 缩略图大小
    ''' </summary>
    ''' <remarks></remarks>
    Private Const INT_ContentThumbnailImageSize As Integer = 200
    ''' <summary>
    ''' 图片 缩略图大小
    ''' </summary>
    ''' <remarks></remarks>
    Private Const INT_PictureThumbnailSize As Integer = 600

#If DEBUG Then

    Private Shared instanceCount As Long
    Dim sw As New Stopwatch

#End If

    Sub New()
        'ConfigManager.ResetSettings()

#If DEBUG Then
        sw.Start()
        Debug.WriteLine("Create Instance now , Now have count of Instances is " & Interlocked.Increment(instanceCount))
#End If

    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()

#If DEBUG Then
        sw.Stop()
        Debug.WriteLine("Finalize Instance,Now have count of Instances is " & Interlocked.Decrement(instanceCount))
        Debug.WriteLine(String.Format("This Instance is Running Time:{0}  , {1} ms , {2} Ticks", sw.Elapsed, sw.ElapsedMilliseconds, sw.ElapsedTicks))
#End If

    End Sub


#Region " 函数"


    ''' <summary>
    ''' 设置 文化（语言）
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared Sub SetCulture()
        Dim webcontext = WebOperationContext.Current

        If webcontext IsNot Nothing Then
            Dim langs = webcontext.IncomingRequest.Headers("Accept-Language").Split(",".ToArray, StringSplitOptions.RemoveEmptyEntries)

            Dim lang = langs.FirstOrDefault

            If lang.IsNotNullOrEmpty Then
                My.Application.ChangeCulture(lang)
                My.Application.ChangeUICulture(lang)
            End If

        End If
    End Sub


    ''' <summary>
    ''' 建立Feed
    ''' </summary>
    ''' <param name="title">标题 </param>
    ''' <param name="description">描述</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function CreateFeed(ByVal title As String, ByVal description As String) As SyndicationFeed

        Dim feed As New SyndicationFeed()

        With feed
            .Title = New TextSyndicationContent(title)
            .Description = New TextSyndicationContent(description)
            .Generator = "Comic Services"
            .Copyright = New TextSyndicationContent(ConfigManager.GetSettings.Copyright.Value)
            .Authors.Add(New SyndicationPerson(ConfigManager.GetSettings.AuthorEmail.Value, ConfigManager.GetSettings.AuthorName.Value, String.Empty))
            .LastUpdatedTime = DateTime.Now
        End With

        Return feed
    End Function





#Region " Convert ..."




    ''' <summary>
    ''' 转换 Comic 列表  
    ''' </summary>
    ''' <param name="comics"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function ConvertComicList(ByVal comics As IEnumerable(Of Comic)) As IEnumerable(Of SyndicationItem)
        Dim items As New List(Of SyndicationItem)

        For Each c In comics

            Dim item As New SyndicationItem()

            item.Title = New TextSyndicationContent(c.Title)
            'item.Copyright = New TextSyndicationContent(ConfigManager.GetSettings.Copyright.Value)
            'item.Authors.Add(New SyndicationPerson(ConfigManager.GetSettings.AuthorEmail.Value, ConfigManager.GetSettings.AuthorName.Value, String.Empty))

            item.PublishDate = c.DateCreated
            item.LastUpdatedTime = c.DateModified

            Dim comicUri = BuildComicUri(ServiceUris.GetComic, c)

            Dim imageUri = BuildComicUri(ServiceUris.GetComicImage, c)
            Dim imageThumbUri = BuildComicUri(ServiceUris.GetComicThumbnailImage, c)


            item.Id = comicUri.ToString()

            With item.Links
                .Add(New SyndicationLink(comicUri))
                .Add(New SyndicationLink(imageUri))
                .Add(New SyndicationLink(imageThumbUri))
            End With

            Dim html As String = GetComicItemHtml(comicUri, imageUri, imageThumbUri, c.Title, c.Description)


            item.Content = SyndicationContent.CreateHtmlContent(html)

            items.Add(item)
        Next
        Return items
    End Function



    ''' <summary>
    ''' 转换 Comic centent 列表  
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function ConvertContentList(ByVal contents As IEnumerable(Of ComicContent)) As IEnumerable(Of SyndicationItem)
        Dim items As New List(Of SyndicationItem)

        For Each c In contents

            Dim item As New SyndicationItem()

            item.Title = New TextSyndicationContent(c.Title)
            'item.Copyright = New TextSyndicationContent(ConfigManager.GetSettings.Copyright.Value)
            'item.Authors.Add(New SyndicationPerson(ConfigManager.GetSettings.AuthorEmail.Value, ConfigManager.GetSettings.AuthorName.Value, String.Empty))

            item.PublishDate = c.DateCreated
            item.LastUpdatedTime = c.DateModified

            Dim comicContentUri As Uri
            Dim imageUri As Uri
            Dim imageThumbUri As Uri

            item.Categories.Add(New SyndicationCategory(c.ItemType.ToString))

            If c.ItemType = ContentType.Chapter Then

                comicContentUri = BuildContentUri(ServiceUris.GetComicChapter, c)
                imageUri = BuildContentUri(ServiceUris.GetChapterImage, c)
                imageThumbUri = BuildContentUri(ServiceUris.GetChapterThumbnailImage, c)

            ElseIf c.ItemType = ContentType.Vol Then

                comicContentUri = BuildContentUri(ServiceUris.GetComicVol, c)
                imageUri = BuildContentUri(ServiceUris.GetVolImage, c)
                imageThumbUri = BuildContentUri(ServiceUris.GetVolThumbnailImage, c)

            Else

                comicContentUri = New Uri("unknow")
                imageUri = New Uri("unknow")
                imageThumbUri = New Uri("unknow")

            End If




            item.Id = comicContentUri.ToString()

            With item.Links
                .Add(New SyndicationLink(comicContentUri))
                .Add(New SyndicationLink(imageUri))
                .Add(New SyndicationLink(imageThumbUri))
            End With



            Dim html As String = GetContentItemHtml(comicContentUri, imageUri, imageThumbUri, c.Title).ToString


            item.Content = SyndicationContent.CreateHtmlContent(html)

            items.Add(item)
        Next
        Return items
    End Function

    ''' <summary>
    ''' 转换 Picture 列表  
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function ConvertPictureList(ByVal pictures As IEnumerable(Of Picture)) As IEnumerable(Of SyndicationItem)
        Dim items As New List(Of SyndicationItem)

        For Each p In pictures



            Dim item As New SyndicationItem()

            item.Title = New TextSyndicationContent(p.Id)
            'item.Copyright = New TextSyndicationContent(ConfigManager.GetSettings.Copyright.Value)
            'item.Authors.Add(New SyndicationPerson(ConfigManager.GetSettings.AuthorEmail.Value, ConfigManager.GetSettings.AuthorName.Value, String.Empty))

            item.PublishDate = p.DateCreated
            item.LastUpdatedTime = p.DateModified




            Dim pictureUri As Uri
            Dim pictureThumbUri As Uri

            If p.ItemType = ContentType.Chapter Then

                pictureUri = BuildPictureUri(ServiceUris.GetPictureFromChapter, p)
                pictureThumbUri = BuildPictureUri(ServiceUris.GetPictureThumbnailFromChapter, p)

            ElseIf p.ItemType = ContentType.Vol Then

                pictureUri = BuildPictureUri(ServiceUris.GetPictureFromVol, p)
                pictureThumbUri = BuildPictureUri(ServiceUris.GetPictureThumbnailFromVol, p)

            Else

                pictureUri = New Uri("Unknow")
                pictureThumbUri = New Uri("Unknow")

            End If


            item.Id = pictureUri.ToString()
            item.Links.Add(New SyndicationLink(pictureUri, "enclosure", p.FileName, p.MimeType, p.Size))
            item.Links.Add(New SyndicationLink(pictureUri))


            Dim html As String = GetPictureItemHtml(pictureUri, pictureThumbUri)

            item.Content = SyndicationContent.CreateHtmlContent(html)

            items.Add(item)

        Next
        Return items
    End Function

#End Region


#Region "HTML "

    ''' <summary>
    ''' 用于显示 漫画 列表 元素的HTML
    ''' </summary>
    ''' <param name="comicUri"> 漫画的URI</param>
    ''' <param name="Description"> 描述</param>
    ''' <param name="imageThumbUri">缩略图的URI</param>
    ''' <param name="imageUri">图像的URI</param>
    ''' <param name="Title">标题</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function GetComicItemHtml(ByVal comicUri As Uri, ByVal imageUri As System.Uri, ByVal imageThumbUri As System.Uri, ByVal Title As String, ByVal Description As String) As String
        Dim html = <div>
                       <div>
                       </div>
                       <div align="center" scope="col" valign="middle" style="width: 300px; float: left">
                           <a href=<%= imageUri %>>
                               <img src=<%= imageThumbUri %> style="vertical-align: middle; text-align: center;"/>
                           </a>
                       </div>
                       <div style="position: relative;">
                           <div>
                               <a href=<%= comicUri %> style="font-size: 20px; font-weight: bold;">
                                   <%= Title %>
                               </a>
                           </div>
                           <div>
                               <%= Description %>
                           </div>
                       </div>
                   </div>

        Return html.ToString
    End Function

    ''' <summary>
    ''' 用于显示 漫画内容 列表 元素的HTML
    ''' </summary>
    ''' <param name="comicContentUri">内容 URI </param>
    ''' <param name="imageUri"> 图像 URI</param>
    ''' <param name="imageThumbUri"> 缩略图 URI</param>
    ''' <param name="Title">标题 </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function GetContentItemHtml(ByVal comicContentUri As Uri, ByVal imageUri As Uri, ByVal imageThumbUri As Uri, ByVal Title As String) As String
        Dim html = <div>
                       <div>
                           <a href=<%= comicContentUri %> style="font-size: 20px; font-weight: bold; "><%= Title %></a>
                       </div>
                       <div>
                           <a href=<%= imageUri %>>
                               <img src=<%= imageThumbUri %> border="0" alt=""/>
                           </a>
                       </div>
                   </div>
        Return html.ToString
    End Function

    ''' <summary>
    ''' 用于显示 图片 列表 元素的HTML
    ''' </summary>
    ''' <param name="pictureUri">图片 URI</param>
    ''' <param name="pictureThumbUri"> 图片 缩略图 URI </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function GetPictureItemHtml(ByVal pictureUri As Uri, ByVal pictureThumbUri As Uri) As String
        Dim html = <p>
                       <a href=<%= pictureUri %>>
                           <img src=<%= pictureThumbUri %> border="0"/>
                       </a>
                   </p>



        Return html.ToString()
    End Function


    ''' <summary>
    ''' 获取用于输出 Comic 的HTML
    ''' </summary>
    ''' <param name="title">标题</param>
    ''' <param name="Description">描述</param>
    ''' <param name="chaptersUri">章URI</param>
    ''' <param name="volsUri">卷URI</param>
    ''' <param name="comicRssUri">漫画  RSS</param>
    ''' <param name="comicAtomUri">漫画 Atom</param>
    ''' <param name="volsRssUri">卷 RSS</param>
    ''' <param name="volsAtomUri">卷 Atom</param>
    ''' <param name="chaptersRssUri"> 章 RSS</param>
    ''' <param name="chaptersAtomUri"> 章 Atom</param>
    ''' <param name="Chapters">章</param>
    ''' <param name="vols">卷</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function GetComicHtml(ByVal title As String, _
                                         ByVal Description As String, _
                                         ByVal imageUri As Uri, _
                                         ByVal imageThumbUri As Uri, _
                                         ByVal chaptersUri As Uri, _
                                         ByVal volsUri As Uri, _
                                         ByVal comicRssUri As Uri, _
                                         ByVal comicAtomUri As Uri, _
                                         ByVal volsRssUri As Uri, _
                                         ByVal volsAtomUri As Uri, _
                                         ByVal chaptersRssUri As Uri, _
                                         ByVal chaptersAtomUri As Uri, _
                                         ByVal Chapters As System.Collections.Generic.IEnumerable(Of ComicContent), _
                                         ByVal vols As System.Collections.Generic.IEnumerable(Of ComicContent)) As String






        Dim html = <html xmlns="http://www.w3.org/1999/xhtml">
                       <head>
                           <title><%= title %></title>
                           <link rel="alternate" type="application/rss+xml" title=<%= title & " RSS" %> href=<%= comicRssUri %>/>
                           <link rel="alternate" type="application/atom+xml" title=<%= title & " Atom" %> href=<%= comicAtomUri %>/>
                           <link rel="alternate" type="application/rss+xml" title=<%= title & " Vols RSS" %> href=<%= volsRssUri %>/>
                           <link rel="alternate" type="application/atom+xml" title=<%= title & " Vols Atom" %> href=<%= volsAtomUri %>/>
                           <link rel="alternate" type="application/rss+xml" title=<%= title & " Chapters RSS" %> href=<%= chaptersRssUri %>/>
                           <link rel="alternate" type="application/atom+xml" title=<%= title & " Chapters Atom" %> href=<%= chaptersAtomUri %>/>
                       </head>
                       <body>
                           <div>
                               <div>
                                   <div style="font-size: 20px; font-weight: bold; ">
                                       <%= title %>
                                   </div>
                                   <div align="right" style="font-size:  9px; ">
                                       <img src=<%= GetFeedIconUri() %>/>
                                       <a href=<%= comicRssUri %> style="font-size:  9px; ">RSS</a>
                                        / 
                                       <a href=<%= comicRssUri %> style="font-size:  9px; ">Atom</a>
                                   </div>
                               </div>
                               <hr/>
                               <div>
                                   <div align="center" scope="col" valign="middle" style="width: 300px; float:left">
                                       <a href=<%= imageUri %>>
                                           <img src=<%= imageThumbUri %> alt=""
                                               style="vertical-align: middle; text-align: center; "/>
                                       </a>
                                   </div>
                                   <div style=<%= "position: relative; height:" & INT_ComicThumbnailImageSize & "px;" %>>
                                       <%= Description %>
                                   </div>
                               </div>
                               <br/>
                               <hr/>
                               <br/>
                               <div>
                                   <span>
                                       <%= My.Resources.HtmlVols %>
                                   </span>
                                   <hr style="height:1px"/>
                                   <div>
                                       <%= From v In vols _
                                           Select <div>
                                                      <a href=<%= BuildContentUri(ServiceUris.GetComicVol, v) %>>
                                                          <%= v.Title %>
                                                      </a>
                                                  </div> %>

                                   </div>
                                   <div style="text-align: right;font-size: 12px; ">
                                       <img src=<%= GetFeedIconUri() %>/>
                                       <a href=<%= volsUri %> style="font-size: 12px; "><%= My.Resources.HtmlViewAllVols %></a>
                                      (
                                      <a href=<%= volsRssUri %> style="font-size:  9px; ">RSS</a>
                                       / 
                                      <a href=<%= volsAtomUri %> style="font-size: 9px; ">Atom</a>
                                       )
                                  </div>
                               </div>
                               <div>
                                   <span>
                                       <%= My.Resources.HtmlChapters %>
                                   </span>
                                   <hr style="height:1px"/>
                                   <div>
                                       <%= From c In Chapters _
                                           Select <div>
                                                      <a href=<%= BuildContentUri(ServiceUris.GetComicChapter, c) %>>
                                                          <%= c.Title %>
                                                      </a>
                                                  </div> %>
                                   </div>
                                   <div style="text-align: right;font-size:  12px;">
                                       <img src=<%= GetFeedIconUri() %>/>
                                       <a href=<%= chaptersUri %> style="font-size:  12px; "><%= My.Resources.HtmlViewAllChapters %></a>
                                      (
                                      <a href=<%= chaptersRssUri %> style="font-size:  9px; ">RSS</a>
                                      /
                                      <a href=<%= chaptersAtomUri %> style="font-size:  9px; ">Atom</a>
                                      )
                                  </div>
                               </div>
                           </div>
                       </body>
                   </html>

        Return html.ToString
    End Function

    ''' <summary>
    ''' 获取用于输出 Vol OR Chapter 的HTML
    ''' </summary>
    ''' <param name="title">标题</param>
    ''' <param name="count">图片数量</param>
    ''' <param name="RssUri"> RSS</param>
    ''' <param name="AtomUri"> Atom </param>
    ''' <param name="picturelist">图片列表</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function GetContentHtml(ByVal title As String, ByVal count As Integer, ByVal RssUri As Uri, ByVal AtomUri As Uri, ByVal picturelist As System.Collections.Generic.List(Of Picture)) As String
        Dim html = <html xmlns="http://www.w3.org/1999/xhtml">
                       <head>
                           <title><%= title %></title>
                           <link rel="alternate" type="application/rss+xml" title=<%= title & " RSS" %> href=<%= RssUri %>/>
                           <link rel="alternate" type="application/atom+xml" title=<%= title & " Atom" %> href=<%= AtomUri %>/>
                       </head>
                       <body>
                           <div>
                               <div style="font-size: 20px; font-weight: bold; ">
                                   <%= title %>
                               </div>
                           </div>
                           <div>
                               <div style="font-size: 9px; float: right;" align="right">
                                   <img src=<%= GetFeedIconUri() %>/>
                                   <a href=<%= RssUri %>>RSS</a>
                                    /
                                   <a href=<%= AtomUri %>>Atom</a>
                               </div>
                               <div style="font-size: x-small; position: relative;">
                                   <span><%= My.Resources.HtmlNumberofCount %></span><span><b><%= count %></b></span>
                               </div>
                           </div>
                           <hr/>
                           <div>
                               <%= From p In picturelist _
                                   Select <div>
                                              <img src=<%= BuildPictureUri(ServiceUris.GetPictureFromVol, p) %> border="0" alt=""/>
                                              <br/>
                                          </div> %>
                           </div>
                       </body>
                   </html>

        Return html.ToString
    End Function
    ''' <summary>
    ''' 获取用于出现错误时显示的 HTML
    ''' </summary>
    ''' <param name="message"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function GetErrorHtml(Optional ByVal message As String = "") As String
        Dim html = <html xmlns="http://www.w3.org/1999/xhtml">
                       <head>
                           <title>ERROR</title>
                       </head>
                       <body>
                           <div>
                               <div style="font-size: 20px; font-weight: bold; "><%= My.Resources.HtmlError %></div>
                               <p>
                                   <%= message %>
                               </p>
                           </div>
                       </body>
                   </html>

        Return html.ToString
    End Function


#End Region

#Region "Build URI"
    ''' <summary>
    ''' 生成 URI
    ''' </summary>
    ''' <param name="templateUri">使用模板</param>
    ''' <param name="values">参数</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function BuildUri(ByVal templateUri As String, ByVal ParamArray values() As String) As Uri
        Dim baseUri = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri
        Dim pictureUT = New UriTemplate(templateUri)
        Dim pictureUri = pictureUT.BindByPosition(baseUri, values)
        Return New Uri(HttpUtility.UrlDecode(pictureUri.ToString))
    End Function

    ''' <summary>
    ''' 生成 URI
    ''' </summary>
    ''' <param name="templateUri">使用模板</param>
    Private Shared Function BuildComicUri(ByVal templateUri As String, ByVal c As Comic) As Uri
        Return BuildUri(templateUri, c.Id)
    End Function
    ''' <summary>
    ''' 生成 URI
    ''' </summary>
    ''' <param name="templateUri">使用模板</param>
    Private Shared Function BuildContentUri(ByVal templateUri As String, ByVal c As ComicContent) As Uri
        Return BuildUri(templateUri, c.ComicId, c.Id)
    End Function
    ''' <summary>
    ''' 生成 URI
    ''' </summary>
    ''' <param name="templateUri">使用模板</param>
    Private Shared Function BuildPictureUri(ByVal templateUri As String, ByVal p As Picture) As Uri
        Return BuildUri(templateUri, p.ComicId, p.ItemId, p.Id)
    End Function
#End Region




    ''' <summary>
    ''' 设置缓存
    ''' </summary>
    Private Sub SetCaching(ByVal maxCacheAge As Integer)
        Dim Context As WebOperationContext = WebOperationContext.Current
        Dim LastModifiedDate As DateTime = Now

        If Context IsNot Nothing Then

        End If

    End Sub
    ''' <summary>
    ''' 设置缓存
    ''' </summary>
    ''' <param name="context"></param>
    ''' <param name="lastModifiedDate"></param>
    ''' <param name="maxCacheAge"></param>
    ''' <remarks></remarks>
    Private Sub SetCaching(ByVal context As WebOperationContext, ByVal lastModifiedDate As DateTime, ByVal maxCacheAge As Integer)
        ' set CacheControl header
        Dim cacheHeader = HttpResponseHeader.CacheControl
        Dim cacheControlValue = String.Format("max-age={0}, must-revalidate", maxCacheAge)
        context.OutgoingResponse.Headers.Set(cacheHeader, cacheControlValue)

        ' set cache validation 
        context.OutgoingResponse.LastModified = lastModifiedDate
        Dim eTag = context.IncomingRequest.UriTemplateMatch.RequestUri.ToString() + lastModifiedDate.ToString()
        context.OutgoingResponse.ETag = eTag
    End Sub

#End Region


    Public Function GetDocumentation() As System.IO.Stream Implements IComicService.GetDocumentation
        SetCulture()
        Dim stream As New MemoryStream()

        Dim writer As New StreamWriter(stream, Encoding.UTF8)
        writer.Write(My.Resources.ServiceDoc)
        writer.Flush()

        stream.Position = 0

        WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"

        '

        Return stream

    End Function



#Region "Cmoics"

    '''<summary>获取漫画列表</summary>
    '''<remarks>返回漫画列表 Feed Atom</remarks>
    Public Function GetComicsAsAtom() As System.ServiceModel.Syndication.Atom10FeedFormatter Implements IComicService.GetComicsAsAtom
        Dim feed = CreateFeed("Comics", "All Comics")

        Dim list = ComicManager.GetComics

        feed.Items = ConvertComicList(list.OrderBy(Function(x) (x.Title)))

        Return feed.GetAtom10Formatter()
    End Function

    '''<summary>获取漫画列表</summary>
    '''<remarks>返回漫画列表 Feed RSS</remarks>
    Public Function GetComicsAsRss() As System.ServiceModel.Syndication.Rss20FeedFormatter Implements IComicService.GetComicsAsRss
        Dim feed = CreateFeed("Comics", "All Comics")

        Dim list = ComicManager.GetComics

        feed.Items = ConvertComicList(list.OrderBy(Function(x) (x.Title)))
        Return feed.GetRss20Formatter
    End Function

    '''<summary>获取漫画列表（默认）</summary>
    '''<remakrs>返回漫画列表 Feed 默认格式</remakrs>
    Public Function GetComicsinDefaultFormat() As System.ServiceModel.Syndication.SyndicationFeedFormatter Implements IComicService.GetComicsinDefaultFormat
        Return GetComicsAsRss()
    End Function


#End Region

#Region "Comic"

    '''<summary>获取漫画</summary>
    '''<remarks>返回指定漫画 Feed Atom</remarks>
    ''' <param name="comicId">漫画Id</param>
    Public Function GetComicAsAtom(ByVal comicId As String) As System.ServiceModel.Syndication.Atom10FeedFormatter Implements IComicService.GetComicAsAtom
        SetCulture()
        If comicId.IsNotNullOrEmpty Then

            Dim comic = ComicManager.GetComicById(comicId)

            Dim feed = CreateFeed(comic.Title, comic.Description)
            Dim Chapters = ComicManager.GetComicChapters(comicId)
            Dim vols = ComicManager.GetComicVols(comicId)

            Dim list = Chapters.Union(vols)


            feed.Items = ConvertContentList(list.OrderByDescending(Function(x) (x.DateModified)))

            Return feed.GetAtom10Formatter()

        Else
            Return CreateFeed("ERROR", "").GetAtom10Formatter
        End If
    End Function

    '''<summary>获取漫画</summary>
    '''<remarks>返回指定漫画 Feed RSS</remarks>
    Public Function GetComicAsRss(ByVal comicId As String) As System.ServiceModel.Syndication.Rss20FeedFormatter Implements IComicService.GetComicAsRss
        SetCulture()
        If comicId.IsNotNullOrEmpty Then

            Dim comic = ComicManager.GetComicById(comicId)

            Dim feed = CreateFeed(comic.Title, comic.Description)
            Dim Chapters = ComicManager.GetComicChapters(comicId)
            Dim vols = ComicManager.GetComicVols(comicId)

            Dim list = Chapters.Union(vols)


            feed.Items = ConvertContentList(list.OrderByDescending(Function(x) (x.DateModified)))

            Return feed.GetRss20Formatter()

        Else
            Return CreateFeed("ERROR", "").GetRss20Formatter
        End If
    End Function


    '''<summary>获取漫画（默认）</summary>
    '''<remakrs>返回指定漫画 </remakrs>
    ''' <param name="comicId">漫画Id</param>
    Public Function GetComic(ByVal comicId As String) As System.IO.Stream Implements IComicService.GetComic
        SetCulture()

        Dim stream As New MemoryStream()
        Dim writer As New StreamWriter(stream, Encoding.UTF8)

        If comicId.IsNotNullOrEmpty Then

            Dim comic = ComicManager.GetComicById(comicId)

            If comic IsNot Nothing Then



                Const intLastUpdatedNumber As Integer = 5

                Dim Chapters = ComicManager.GetComicChapters(comicId).OrderByDescending(Function(x) (x.DateModified)).Take(intLastUpdatedNumber)
                Dim vols = ComicManager.GetComicVols(comicId).OrderByDescending(Function(x) (x.DateModified)).Take(intLastUpdatedNumber)




                Dim title As String = comic.Title
                Dim Description As String = comic.Description
                Dim volsUri As Uri = BuildComicUri(ServiceUris.GetComicVols, comic)
                Dim chaptersUri As Uri = BuildComicUri(ServiceUris.GetComicChapters, comic)

                Dim imageUri = BuildComicUri(ServiceUris.GetComicImage, comic)
                Dim imageThumbUri = BuildComicUri(ServiceUris.GetComicThumbnailImage, comic)

                Dim comicRssUri As Uri = BuildComicUri(ServiceUris.GetComicAsRss, comic)
                Dim comicAtomUri As Uri = BuildComicUri(ServiceUris.GetComicAsAtom, comic)
                Dim volsRssUri As Uri = BuildComicUri(ServiceUris.GetComicVolsAsRss, comic)
                Dim volsAtomUri As Uri = BuildComicUri(ServiceUris.GetComicVolsAsAtom, comic)
                Dim chaptersRssUri As Uri = BuildComicUri(ServiceUris.GetComicChaptersAsRss, comic)
                Dim chaptersAtomUri As Uri = BuildComicUri(ServiceUris.GetComicChaptersAsAtom, comic)

                Dim html As String = GetComicHtml(title, _
                                                  Description, _
                                                  imageUri, _
                                                  imageThumbUri, _
                                                  chaptersUri, _
                                                  volsUri, _
                                                  comicRssUri, _
                                                  comicAtomUri, _
                                                  volsRssUri, _
                                                  volsAtomUri, _
                                                  chaptersRssUri, _
                                                  chaptersAtomUri, _
                                                  Chapters, _
                                                  vols)

                writer.Write(html)

            Else
                writer.Write(GetErrorHtml)
            End If
        Else
            Dim html = GetErrorHtml()
            writer.Write(html)

        End If

        writer.Flush()

        stream.Position = 0

        WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"
        Return stream


    End Function


#End Region


#Region "Vols"


    '''<summary>获取卷（Vols）</summary>
    '''<remarks>返回漫画的卷 Feed Atom</remarks>
    ''' <param name="comicId">漫画Id</param>
    Public Function GetComicVolsAsAtom(ByVal comicId As String) As System.ServiceModel.Syndication.Atom10FeedFormatter Implements IComicService.GetComicVolsAsAtom
        SetCulture()
        If comicId.IsNotNullOrEmpty Then

            Dim comic = ComicManager.GetComicById(comicId)

            Dim feed = CreateFeed(comic.Title, comic.Description)

            Dim vols = ComicManager.GetComicVols(comicId)


            feed.Items = ConvertContentList(vols.OrderBy(Function(x) (x.Title)))

            Return feed.GetAtom10Formatter()
        Else
            Return CreateFeed("ERROR", "").GetAtom10Formatter
        End If
    End Function


    '''<summary>获取卷（Vols）</summary>
    '''<remarks>返回漫画的卷 Feed RSS</remarks>
    ''' <param name="comicId">漫画Id</param>
    Public Function GetComicVolsAsRss(ByVal comicId As String) As System.ServiceModel.Syndication.Rss20FeedFormatter Implements IComicService.GetComicVolsAsRss
        SetCulture()
        If comicId.IsNotNullOrEmpty Then

            Dim comic = ComicManager.GetComicById(comicId)

            Dim feed = CreateFeed(comic.Title, comic.Description)

            Dim vols = ComicManager.GetComicVols(comicId)


            feed.Items = ConvertContentList(vols.OrderBy(Function(x) (x.Title)))

            Return feed.GetRss20Formatter()
        Else
            Return CreateFeed("ERROR", "").GetRss20Formatter
        End If
    End Function

    '''<summary>获取卷（Vols）（默认）</summary>
    '''<remakrs>返回漫画的卷 </remakrs>
    ''' <param name="comicId">漫画Id</param>
    Public Function GetComicVols(ByVal comicId As String) As System.ServiceModel.Syndication.SyndicationFeedFormatter Implements IComicService.GetComicVols
        Return GetComicVolsAsRss(comicId)
    End Function



#End Region


#Region "Chapters"

    '''<summary>获取章（Chapters）</summary>
    '''<remarks>返回漫画的章 Feed Atom</remarks>
    ''' <param name="comicId">漫画Id</param>
    Public Function GetComicChaptersAsAtom(ByVal comicId As String) As System.ServiceModel.Syndication.Atom10FeedFormatter Implements IComicService.GetComicChaptersAsAtom
        If comicId.IsNotNullOrEmpty Then

            Dim comic = ComicManager.GetComicById(comicId)

            Dim feed = CreateFeed(comic.Title, comic.Description)
            Dim Chapters = ComicManager.GetComicChapters(comicId)

            feed.Items = ConvertContentList(Chapters.OrderBy(Function(x) (x.Title)))


            Return feed.GetAtom10Formatter()
        Else
            Return CreateFeed("ERROR", "").GetAtom10Formatter()
        End If
    End Function

    '''<summary>获取章（Chapters）</summary>
    '''<remarks>返回漫画的章 Feed RSS</remarks>
    ''' <param name="comicId">漫画Id</param>
    Public Function GetComicChaptersAsRss(ByVal comicId As String) As System.ServiceModel.Syndication.Rss20FeedFormatter Implements IComicService.GetComicChaptersAsRss
        If comicId.IsNotNullOrEmpty Then

            Dim comic = ComicManager.GetComicById(comicId)

            Dim feed = CreateFeed(comic.Title, comic.Description)
            Dim Chapters = ComicManager.GetComicChapters(comicId)

            feed.Items = ConvertContentList(Chapters.OrderBy(Function(x) (x.Title)))

            Return feed.GetRss20Formatter()
        Else
            Return CreateFeed("ERROR", "").GetRss20Formatter
        End If
    End Function


    '''<summary>获取章（Chapters）（默认）</summary>
    '''<remakrs>返回漫画的章 Feed 默认格式</remakrs>
    ''' <param name="comicId">漫画Id</param>
    Public Function GetComicChapters(ByVal comicId As String) As System.ServiceModel.Syndication.SyndicationFeedFormatter Implements IComicService.GetComicChapters
        Return GetComicChaptersAsRss(comicId)
    End Function


#End Region


#Region " Vol "

    '''<summary>获取卷（Vol）</summary>
    '''<remakrs>返回漫画的卷 </remakrs>
    ''' <param name="comicId">漫画Id</param>
    '''<param name="volId">卷 Id</param>
    Public Function GetComicVol(ByVal comicId As String, ByVal volId As String) As System.IO.Stream Implements IComicService.GetComicVol
        SetCulture()

        Dim stream As New MemoryStream()
        Dim writer As New StreamWriter(stream, Encoding.UTF8)

        If comicId.IsNotNullOrEmpty AndAlso volId.IsNotNullOrEmpty Then


            Dim Vol = ComicManager.GetComicVolById(comicId, volId)

            If Vol IsNot Nothing Then

                Dim title As String = Vol.Title
                Dim count As Integer = Vol.Items.Count
                Dim rssUri As Uri = BuildContentUri(ServiceUris.GetComicVolAsRss, Vol)
                Dim atomUri As Uri = BuildContentUri(ServiceUris.GetComicVolAsAtom, Vol)
                Dim picturelist = Vol.Items.OrderBy(Function(x) (x.FileName)).ToList

                Dim html As String = GetContentHtml(title, count, rssUri, atomUri, picturelist)

                writer.Write(html)

            Else
                writer.Write(GetErrorHtml)
            End If
        Else
            Dim html = GetErrorHtml()
            writer.Write(html)

        End If

        writer.Flush()

        stream.Position = 0

        WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"
        Return stream

    End Function

    '''<summary>获取卷（Vol）</summary>
    '''<remarks>返回漫画的卷 Feed Atom</remarks>
    '''<param name="comicId">漫画Id</param>
    '''<param name="volId">卷 Id</param>
    Public Function GetComicVolAsAtom(ByVal comicId As String, ByVal volId As String) As System.ServiceModel.Syndication.Atom10FeedFormatter Implements IComicService.GetComicVolAsAtom
        SetCulture()
        If comicId.IsNotNullOrEmpty AndAlso volId.IsNotNullOrEmpty Then

            Dim Vol = ComicManager.GetComicVolById(comicId, volId)

            Dim feed = CreateFeed(Vol.Title, "")


            feed.Items = ConvertPictureList(Vol.Items.OrderBy(Function(x) (x.FileName)))
            Return feed.GetAtom10Formatter()
        Else
            Return CreateFeed("ERROR", "").GetAtom10Formatter()
        End If
    End Function


    '''<summary>获取卷（Vol）</summary>
    '''<remarks>返回漫画的卷 Feed RSS</remarks>
    '''<param name="comicId">漫画Id</param>
    '''<param name="volId">卷 Id</param>
    Public Function GetComicVolAsRss(ByVal comicId As String, ByVal volId As String) As System.ServiceModel.Syndication.Rss20FeedFormatter Implements IComicService.GetComicVolAsRss
        SetCulture()
        If comicId.IsNotNullOrEmpty AndAlso volId.IsNotNullOrEmpty Then

            Dim Vol = ComicManager.GetComicVolById(comicId, volId)

            Dim feed = CreateFeed(Vol.Title, "")


            feed.Items = ConvertPictureList(Vol.Items.OrderBy(Function(x) (x.FileName)))

            Return feed.GetRss20Formatter()
        Else
            Return CreateFeed("ERROR", "").GetRss20Formatter()
        End If
    End Function



#End Region

#Region "Chapter"

    '''<summary>获取章（Chapter）</summary>
    '''<remakrs>返回漫画的章</remakrs>
    '''<param name="comicId">漫画Id</param>
    '''<param name="chapterId">章Id</param>
    Public Function GetComicChapter(ByVal comicId As String, ByVal chapterId As String) As System.IO.Stream Implements IComicService.GetComicChapter
        SetCulture()

        Dim stream As New MemoryStream()
        Dim writer As New StreamWriter(stream, Encoding.UTF8)

        If comicId.IsNotNullOrEmpty AndAlso chapterId.IsNotNullOrEmpty Then


            Dim chapter = ComicManager.GetComicChapterById(comicId, chapterId)

            If chapter IsNot Nothing Then
                Dim title As String = chapter.Title
                Dim count As Integer = chapter.Items.Count
                Dim rssUri As Uri = BuildContentUri(ServiceUris.GetComicChapterAsRss, chapter)
                Dim atomUri As Uri = BuildContentUri(ServiceUris.GetComicChapterAsAtom, chapter)
                Dim picturelist = chapter.Items.OrderBy(Function(x) (x.FileName)).ToList


                Dim html As String = GetContentHtml(title, count, rssUri, atomUri, picturelist)
                writer.Write(html)

            Else
                writer.Write(GetErrorHtml)
            End If
        Else
            Dim html = GetErrorHtml()
            writer.Write(html)

        End If

        writer.Flush()

        stream.Position = 0

        WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"
        Return stream

    End Function

    '''<summary>获取章（Chapter）</summary>
    '''<remarks>返回漫画的章 Feed Atom</remarks>
    '''<param name="comicId">漫画Id</param>
    '''<param name="chapterId">章Id</param>
    Public Function GetComicChapterAsAtom(ByVal comicId As String, ByVal chapterId As String) As System.ServiceModel.Syndication.Atom10FeedFormatter Implements IComicService.GetComicChapterAsAtom
        SetCulture()
        If comicId.IsNotNullOrEmpty AndAlso chapterId.IsNotNullOrEmpty Then

            Dim chapter = ComicManager.GetComicChapterById(comicId, chapterId)

            Dim feed = CreateFeed(chapter.Title, "")

            feed.Items = ConvertPictureList(chapter.Items.OrderBy(Function(x) (x.FileName)))

            Return feed.GetAtom10Formatter()
        Else
            Return CreateFeed("ERROR", "").GetAtom10Formatter()
        End If
    End Function

    '''<summary>获取章（Chapter）</summary>
    '''<remarks>返回漫画的章 Feed RSS</remarks>
    '''<param name="comicId">漫画Id</param>
    '''<param name="chapterId">章Id</param>
    Public Function GetComicChapterAsRss(ByVal comicId As String, ByVal chapterId As String) As System.ServiceModel.Syndication.Rss20FeedFormatter Implements IComicService.GetComicChapterAsRss
        SetCulture()
        If comicId.IsNotNullOrEmpty AndAlso chapterId.IsNotNullOrEmpty Then

            Dim chapter = ComicManager.GetComicChapterById(comicId, chapterId)

            Dim feed = CreateFeed(chapter.Title, "")

            Dim items As IOrderedEnumerable(Of Picture) = chapter.Items.OrderBy(Function(x) (x.FileName))
            feed.Items = ConvertPictureList(items)

            Return feed.GetRss20Formatter()
        Else
            Return CreateFeed("ERROR", "").GetRss20Formatter()
        End If
    End Function

#End Region


#Region " Image & Picture "


    ''' <summary>
    ''' 获取图像流
    ''' </summary>
    ''' <param name="imageUri">图像 URI</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function GetImage(ByVal imageUri As Uri) As Stream
        'SetCulture()
        Dim stream As MemoryStream
        Using client As New WebClient
            Dim buffer = client.DownloadData(imageUri)
            stream = New MemoryStream(buffer)
        End Using
        Return stream
    End Function



    ''' <summary>
    ''' 获取图像缩略图 流
    ''' </summary>
    ''' <param name="imageUri">图像 URI</param>
    ''' <param name="size">缩略图大小</param>
    ''' <param name="extensionName">扩展名</param>
    ''' <param name="prefix">标记前缀</param>
    Private Shared Function GetImageThumbnail(ByVal imageUri As Uri, ByVal size As Integer, Optional ByVal extensionName As String = "", Optional ByVal prefix As String = "") As Stream
        'SetCulture()
        Dim filepath = Path.Combine(Path.GetTempPath(), prefix & Utils.CalculateMD5Hash(imageUri.ToString()) & extensionName)
        If Not File.Exists(filepath) Then
            Dim buffer As Byte()
            Using client As New WebClient()

                buffer = client.DownloadData(imageUri)
            End Using

            Dim image = Utils.ResizeImageFile(buffer, size)
            File.WriteAllBytes(filepath, image)
        End If
        Dim stream As FileStream = New FileStream(filepath, FileMode.Open, FileAccess.Read)
        Return stream
    End Function


#Region "Picture  "




    '''<summary>获取图片</summary>
    '''<remakrs>返回指定的图片</remakrs>
    '''<param name="comicId">漫画Id</param>
    '''<param name="chapterId">章Id</param>
    '''<param name="pictureId">图片Id</param>
    Public Function GetPictureFromChapter(ByVal ComicId As String, ByVal chapterId As String, ByVal pictureId As String) As System.IO.Stream Implements IComicService.GetPictureFromChapter
        SetCulture()
        If ComicId.IsNotNullOrEmpty AndAlso chapterId.IsNotNullOrEmpty AndAlso pictureId.IsNotNullOrEmpty Then

            Dim p = ComicManager.GetPictureFromChapter(ComicId, chapterId, pictureId)

            If p Is Nothing Then
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
                Return Nothing
            End If

            Dim stream = GetImage(p.ItemUrl)

            ' Set MIME-type
            WebOperationContext.Current.OutgoingResponse.ContentType = p.MimeType

            Return stream
        Else
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
            Return Nothing
        End If

    End Function

    '''<summary>获取图片</summary>
    '''<remakrs>返回指定的图片</remakrs>
    '''<param name="comicId">漫画Id</param>
    '''<param name="volId">卷 Id</param>
    '''<param name="pictureId">图片Id</param>
    Public Function GetPictureFromVol(ByVal comicId As String, ByVal volId As String, ByVal pictureId As String) As System.IO.Stream Implements IComicService.GetPictureFromVol
        SetCulture()
        If comicId.IsNotNullOrEmpty AndAlso volId.IsNotNullOrEmpty AndAlso pictureId.IsNotNullOrEmpty Then

            Dim p = ComicManager.GetPictureFromVol(comicId, volId, pictureId)

            If p Is Nothing Then
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
                Return Nothing
            End If

            Dim stream = GetImage(p.ItemUrl)


            ' Set MIME-type
            WebOperationContext.Current.OutgoingResponse.ContentType = p.MimeType

            Return stream
        Else
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
            Return Nothing
        End If

    End Function


    '''<summary>获取缩略图</summary>
    '''<remakrs>返回指定图片的缩略图</remakrs>
    '''<param name="comicId">漫画Id</param>
    '''<param name="chapterId">章Id</param>
    '''<param name="pictureId">图片Id</param>
    Public Function GetPictureThumbnailFromChapter(ByVal ComicId As String, ByVal chapterId As String, ByVal pictureId As String) As System.IO.Stream Implements IComicService.GetPictureThumbnailFromChapter
        SetCulture()
        If ComicId.IsNotNullOrEmpty AndAlso chapterId.IsNotNullOrEmpty AndAlso pictureId.IsNotNullOrEmpty Then

            Dim p = ComicManager.GetPictureFromChapter(ComicId, chapterId, pictureId)

            If p Is Nothing Then
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
                Return Nothing
            End If

            Dim stream = GetImageThumbnail(p.ItemUrl, INT_PictureThumbnailSize, p.FileExtension)

            ' Set MIME-type
            WebOperationContext.Current.OutgoingResponse.ContentType = p.MimeType

            Return stream
        Else
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
            Return Nothing
        End If
    End Function


    '''<summary>获取缩略图</summary>
    '''<remakrs>返回指定图片的缩略图</remakrs>
    '''<param name="comicId">漫画Id</param>
    '''<param name="volId">卷 Id</param>
    '''<param name="pictureId">图片Id</param>
    Public Function GetPictureThumbnailFromVol(ByVal comicId As String, ByVal volId As String, ByVal pictureId As String) As System.IO.Stream Implements IComicService.GetPictureThumbnailFromVol
        SetCulture()
        If comicId.IsNotNullOrEmpty AndAlso volId.IsNotNullOrEmpty AndAlso pictureId.IsNotNullOrEmpty Then

            Dim p = ComicManager.GetPictureFromVol(comicId, volId, pictureId)

            If p Is Nothing Then
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
                Return Nothing
            End If

            Dim stream = GetImageThumbnail(p.ItemUrl, INT_PictureThumbnailSize, p.FileExtension)

            ' Set MIME-type
            WebOperationContext.Current.OutgoingResponse.ContentType = p.MimeType

            Return stream
        Else
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
            Return Nothing
        End If
    End Function



#End Region

#Region " Image "




    '''<summary>获取漫画图片</summary>
    '''<remakrs>返回指定图片</remakrs>
    '''<param name="comicId">漫画Id</param>
    Public Function GetComicImage(ByVal comicId As String) As System.IO.Stream Implements IComicService.GetComicImage
        SetCulture()
        If comicId.IsNotNullOrEmpty Then

            Dim c = ComicManager.GetComicById(comicId)


            If c Is Nothing Then
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
                Return Nothing
            End If

            Dim stream = GetImage(c.Image)

            ' Set MIME-type
            WebOperationContext.Current.OutgoingResponse.ContentType = c.ImageMimeType

            Return stream
        Else
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
            Return Nothing
        End If
    End Function

    '''<summary>获取漫画图片</summary>
    '''<remakrs>返回指定图片的缩略图</remakrs>
    '''<param name="comicId">漫画Id</param>
    Public Function GetComicThumbnailImage(ByVal comicId As String) As System.IO.Stream Implements IComicService.GetComicThumbnailImage
        SetCulture()
        If comicId.IsNotNullOrEmpty Then

            Dim c = ComicManager.GetComicById(comicId)


            If c Is Nothing Then
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
                Return Nothing
            End If

            Dim stream = GetImageThumbnail(c.Image, INT_ComicThumbnailImageSize, "", "ComicTI")

            ' Set MIME-type
            WebOperationContext.Current.OutgoingResponse.ContentType = c.ImageMimeType

            Return stream
        Else
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
            Return Nothing
        End If
    End Function



    '''<summary>获取卷图片</summary>
    '''<remakrs>返回指定图片</remakrs>
    '''<param name="comicId">漫画Id</param>
    '''<param name="volId">卷 Id</param>
    Public Function GetVolImage(ByVal comicId As String, ByVal volId As String) As System.IO.Stream Implements IComicService.GetVolImage
        SetCulture()
        If comicId.IsNotNullOrEmpty AndAlso volId.IsNotNullOrEmpty Then

            Dim vol = ComicManager.GetComicVolById(comicId, volId)

            If vol Is Nothing Then
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
                Return Nothing
            End If

            Dim stream = GetImage(vol.Image)


            ' Set MIME-type
            WebOperationContext.Current.OutgoingResponse.ContentType = vol.ImageMimeType

            Return stream
        Else
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
            Return Nothing
        End If
    End Function

    '''<summary>获取卷图片</summary>
    '''<remakrs>返回指定图片的缩略图</remakrs>
    '''<param name="comicId">漫画Id</param>
    '''<param name="volId">卷 Id</param>
    Public Function GetVolThumbnailImage(ByVal comicId As String, ByVal volId As String) As System.IO.Stream Implements IComicService.GetVolThumbnailImage
        SetCulture()
        If comicId.IsNotNullOrEmpty AndAlso volId.IsNotNullOrEmpty Then

            Dim vol = ComicManager.GetComicVolById(comicId, volId)

            If vol Is Nothing Then
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
                Return Nothing
            End If

            Dim stream = GetImageThumbnail(vol.Image, INT_ContentThumbnailImageSize, "", "VolTI")

            ' Set MIME-type
            WebOperationContext.Current.OutgoingResponse.ContentType = vol.ImageMimeType

            Return stream
        Else
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
            Return Nothing
        End If
    End Function

    '''<summary>获取章图片</summary>
    '''<remakrs>返回指定图片</remakrs>
    '''<param name="comicId">漫画Id</param>
    Public Function GetChapterImage(ByVal ComicId As String, ByVal chapterId As String) As System.IO.Stream Implements IComicService.GetChapterImage
        SetCulture()
        If ComicId.IsNotNullOrEmpty AndAlso chapterId.IsNotNullOrEmpty Then

            Dim chapter = ComicManager.GetComicChapterById(ComicId, chapterId)

            If chapter Is Nothing Then
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
                Return Nothing
            End If

            Dim stream = GetImage(chapter.Image)


            ' Set MIME-type
            WebOperationContext.Current.OutgoingResponse.ContentType = chapter.ImageMimeType

            Return stream
        Else
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
            Return Nothing
        End If
    End Function

    '''<summary>获取章图片</summary>
    '''<remakrs>返回指定图片的缩略图</remakrs>
    '''<param name="comicId">漫画Id</param>
    Public Function GetChapterThumbnailImage(ByVal ComicId As String, ByVal chapterId As String) As System.IO.Stream Implements IComicService.GetChapterThumbnailImage
        SetCulture()
        If ComicId.IsNotNullOrEmpty AndAlso chapterId.IsNotNullOrEmpty Then

            Dim chapter = ComicManager.GetComicChapterById(ComicId, chapterId)

            If chapter Is Nothing Then
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
                Return Nothing
            End If

            Dim stream = GetImageThumbnail(chapter.Image, INT_ContentThumbnailImageSize, "", "ChapterTI")


            ' Set MIME-type
            WebOperationContext.Current.OutgoingResponse.ContentType = chapter.ImageMimeType

            Return stream
        Else
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
            Return Nothing
        End If
    End Function


#End Region

#End Region

#Region "Resource"
    ''' <summary>
    ''' 获取资源
    ''' </summary>
    ''' <param name="name">资源名字</param>
    Public Function GetResource(ByVal name As String) As System.IO.Stream Implements IComicService.GetResource
        SetCulture()

        If name.IsNotNullOrEmpty Then

            Select Case name.ToLowerInvariant

                Case "feed".ToLowerInvariant

                    Dim ms As New MemoryStream()

                    My.Resources.feed.Save(ms, ImageFormat.Png)

                    ms.Position = 0


                    WebOperationContext.Current.OutgoingResponse.ContentType = "image/png"
                    Return ms

                Case Else

                    WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
                    Return Nothing
            End Select
        Else
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound()
            Return Nothing
        End If
    End Function

    ''' <summary>
    ''' 获取 Feed资源的Uri
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Shared Function GetFeedIconUri() As Uri
        Return BuildUri(ServiceUris.GetResource, "feed")
    End Function

#End Region

#Region "Other...."

    ''' <summary>
    ''' 获取版本
    ''' </summary>
    Public Function GetVerstion() As System.IO.Stream Implements IComicService.GetVerstion
        SetCulture()

        Dim stream As New MemoryStream()
        Dim writer As New StreamWriter(stream, Encoding.UTF8)

        Dim list = From asm In My.Application.Info.LoadedAssemblies _
                   Select asm.GetName.Name, asm.GetName.Version _
                   Order By Name _
                   Where Not Name.StartsWith("System", StringComparison.OrdinalIgnoreCase) _
                   AndAlso Not Name.StartsWith("Microsoft", StringComparison.OrdinalIgnoreCase) _
                   AndAlso Not Name.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase) _
                   AndAlso Not Name.StartsWith("WcfSvcHost", StringComparison.OrdinalIgnoreCase) _
                   AndAlso Not Name.StartsWith("SMDiagnostics", StringComparison.OrdinalIgnoreCase)





        Dim html = <html xmlns="http://www.w3.org/1999/xhtml">
                       <head>
                           <title>Version</title>
                       </head>
                       <body>
                           <div>
                               <%= From item In list _
                                   Select <span><%= item.Name %> : <b><%= item.Version.ToString %></b><br/></span> %>
                           </div>
                       </body>
                   </html>

        writer.Write(html.ToString)

        writer.Flush()

        stream.Position = 0

        WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"
        Return stream

    End Function

#End Region




End Class
